﻿using AutoMapper;
using MediatR;
using S.Services.SheepMale.Api.Application.Command.MarketCommand;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;

namespace S.Services.SheepMale.Api.Application.CommandHandler.MarketCommandHandler
{
    public class MarketUpdCommandHandler : IRequestHandler<MarketUpdCommand, int>
    {

        private readonly IRepository<EntityMarket> entityrepository;


        private readonly IMapper mapper;
        public MarketUpdCommandHandler(IRepository<EntityMarket> entityrepository, IMapper mapper, EntityDbContext entityDbContext)
        {
            this.entityrepository = entityrepository;
            this.mapper = mapper;
        }

        public async Task<int> Handle(MarketUpdCommand request, CancellationToken cancellationToken)
        {
            var result = entityrepository.AllAsync().Result.Where(x => x.Earbugles == request.Earbugles && x.DocumentNumber == request.DocumentNumber && x.MarketId != request.MarketId);
            if (result.Count() != 0)
            {
                return -1;
            }
            request.UpdateDate = DateTime.Now;
			request.TotalPrice = request.SheepNumber * request.PayPrice;
			return await entityrepository.UpdateAsync(mapper.Map<EntityMarket>(request));
        }
    }
}
